// pages/my/my.js
// 模拟数据


//获取应用实例
const app = getApp();
import {
  PATHS_ALIAS, OTHER_INFO
} from '../../utils/api.js'

import {
  http
} from '../../utils/network.js'

import utils  from '../../utils/util.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    checkLogin: '',      //登录信息是否齐全
    userId: wx.getStorageSync('userId'),
    mobile:'',
    windowWidth: '', //窗口宽度
    tabStatus: 'all', //tab控制
    scrollHeight: '600rpx', //滚动box高度
    orderList: [], //订单列表数据
    loadMoreIconShow: false,
    token: wx.getStorageSync('accessToken'), //用户token
    noteTxtLeft: '0', //头部广播滚动定位
    noteShow: true, //头部广播框显示
    conType: 'order', //内容类型显示  order我的订单   group我的拼团
    userInfo: {}, //用户信息
    page:'1',      //分页--页码
    pageSize:'10',      //
    totalPages:'',      //总页码
    orderNo:'',   //活跃的订单号
    orderDetail:'',     //活跃的订单详情
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let _this = this;
    wx.setNavigationBarTitle({
      title: '我的订单',
    });

    wx.getSystemInfo({
      success: function(res) {
        let windowHeight = res.windowHeight;
        let windowWidth = res.windowWidth;
        _this.setData({
          scrollHeight: windowHeight - (windowWidth / 750) * 322 + 'px',
          windowWidth
        })
      }
    });
    // 广播滚动
    this.noteSlide();

  },
  onShow: function() {
    // 检查登录信息
    let checkLogin = this.selectComponent('#loginCheck').checkLogin();
    this.setData({
      checkLogin
    });
    this.setData({
      userId: wx.getStorageSync('userId'),
      token: wx.getStorageSync('accessToken'),
      userInfo: wx.getStorageSync('userInfo'),
      mobile: wx.getStorageSync('mobile'),
      page:1,
      orderList:[]
    });
    if(this.data.checkLogin){
      this.getOrderList(1);
    }
  },
  // 我的拼团/我的订单  切换
  orderAndGroupChange: function(e) {
    let conType = e.currentTarget.dataset.type;
    let tabStatus = '';
    if (conType == 'order') {
      tabStatus = 'all';
      wx.setNavigationBarTitle({
        title: '我的订单',
      })
    } else {
      tabStatus = 'groupAll';
      wx.setNavigationBarTitle({
        title: '我的拼团',
      })
    };
    this.setData({
      conType,
      tabStatus
    });
    this.getOrderList(1);
  },
  // 获取订单列表   是否清空列表   emptyFirst 1是  0否
  getOrderList: function (emptyFirst) {
    // 登录判断
    if (!this.data.checkLogin){
      return
    };
    let _this = this;
    let entryStatus = '';   //订单状态
    let groupOrderStatus = '';    //拼团订单状态
    
    if (emptyFirst == '1') {   //先清空旧列表
      this.setData({
        orderList:[]
      })
    };

    switch (this.data.tabStatus){
      // 我的订单tab
      case 'all':                 //全部
        entryStatus='';
        groupOrderStatus='';
        break
      case 'waitPay':             //待支付
        entryStatus = '04';
        groupOrderStatus = '';
        break
      case 'success':             //报名成功
        entryStatus = '01';
        groupOrderStatus = '';
        break
      case 'refund':            //退款
        entryStatus = 'refund';
        groupOrderStatus = '';
        break
      // 我的拼团tab
      case 'groupAll':           //全部
        entryStatus = '';
        groupOrderStatus = '';
        break
      case 'groupDoing':        //拼团中
        entryStatus = '';
        groupOrderStatus = 'grouping';
        break
      case 'groupSuc':          //拼团成功
        entryStatus = '';
        groupOrderStatus = 'group_success';
        break
      case 'groupFail':         //拼团失败
        entryStatus = '';
        groupOrderStatus = 'group_fail';
        break
    };
    let params = {
      entryStatus: entryStatus,           //	订单状态	string	非必填。	01-报名成功，unjoin-带参与，04-待支付 、finish-已完成， refund-退款的订单
      groupBuy: 'Y', //		是否是拼团订单	string	Y - 拼团订单，N-非拼团订单
      orderType: this.data.conType,       //	订单类型	string	group - 我的拼团，order-我的订单
      groupOrderStatus: groupOrderStatus,         //		拼团订单状态	string	非必填，grouping-拼团中,group_success-拼团成功,group_fail-拼团失败
      mobile: wx.getStorageSync('mobile'), //		手机号	string	必填
      page: this.data.page,               //		页数	string	非必填
      pageSize: this.data.pageSize,                        //		每页大小	string	非必填
      realUserId: this.data.userId,         //		统一用户userId	string	必填
    };
    let orderList = this.data.orderList;
    this.setData({
      loadMoreIconShow: true,
    });
    http({
      path: PATHS_ALIAS.GET_ORDER_LIST,
      params: params,
      success: function(res) {
        // //console.log(res);
        orderList = orderList.concat(res.response.orderList ? res.response.orderList : [])
        _this.setData({
          orderList,
          totalPages: res.response.totalPages?res.response.totalPages:'0'
        });
        _this.setData({
          loadMoreIconShow: false
        });
      },
      fail: function(err) {
        //console.log(err);
      }
    })
  },
  // 重新开团
  beginGroupAgain:function(e){
    //console.log(e);
    wx.navigateTo({
      url: '/pages/actDetail/actDetail?id=' + e.currentTarget.dataset.actid
    })
  },
  // 头部广播走马灯
  noteSlide: function() {
    if (!this.data.noteShow) {
      return
    };
    let _this = this;
    var query = wx.createSelectorQuery();
    //选择id
    query.select('#note_txt').boundingClientRect(function(rect) {
      // //console.log(rect)
      let txtWidth = rect.width;
      let txtBoxWidth = (_this.data.windowWidth / 750) * 594;
      //console.log(txtWidth, txtBoxWidth);
      if (txtWidth <= txtBoxWidth) {
        return;
      } else {
        let timer = setInterval(function() {
          let noteTxtLeft = _this.data.noteTxtLeft;
          if (txtWidth > -noteTxtLeft) {
            noteTxtLeft = noteTxtLeft - 5;
          } else {
            noteTxtLeft = 0;
          };
          _this.setData({
            noteTxtLeft
          });
        }, 200)
      }
    }).exec();
  },
  // 隐藏头部广播
  noteHide: function() {
    this.setData({
      noteShow: false
    })
  },
  // 加载更多
  loadMore: function() {
    let _this = this;
    let orderList = this.data.orderList;
    let page = this.data.page;
    let totalPages = this.data.totalPages;
    if(page == totalPages){
      return;
    }else{
      page = parseInt(page)+1;
      this.setData({
        page
      })
      this.getOrderList();
    }
  },
  // 授权登录
  goLogin: function() {
    if(!this.data.checkLogin){
      this.selectComponent('#loginCheck').loginAgain();
    }
  },
  // 登录成功回调
  loginSuccess: function(e) {
    // //console.log(e);
    if (e.detail.status == '0') {
      this.setData({
        checkLogin: true
      });
      this.onShow();
    }
  },
  // tab切换
  tabChange: function(e) {
    let status = e.currentTarget.dataset.status;
    if(status == this.data.tabStatus){return};
    
    this.setData({
      tabStatus: status,
      page:'1',
      totalPages:'',
    });
    this.getOrderList(1);
  },
  // 支付开始*********************************************************************************
  // 去支付--1、重新获取token   2、提交订单   3、调用平台组支付接口   4、发起微信支付
  goPay: function (e) {
    wx.showLoading({
      title: '支付中',
      mask: true
    });
    this.setData({
      orderNo: e.currentTarget.dataset.orderno
    });
    this.getOrderDetail();
  },
  // 请求订单数据
  getOrderDetail: function () {
    
    let _this = this;
    let params = {
      mobile: this.data.mobile,	          //手机号	string	必填
      orderNo: this.data.orderNo,	          //订单号	string	必填
      realUserId: wx.getStorageSync('userId'),   //	统一用户userId	string	必填
    };
    http({
      path: PATHS_ALIAS.GET_ORDER_DETAIL,
      params: params,
      success: function (res) {
        let orderDetail = res.response.orderDetail;
        _this.setData({
          orderDetail
        });
        _this.loginThird();
      },
      fail: function (err) {
        // //console.log(err);
      }
    })
  },
  // 重新获取token及用户信息，防止token失效
  loginThird: function () {
    let _this = this;
    let params = {
      logType: '07',
      thirdId: wx.getStorageSync('unionId'),
      resId: 'weixin',
      userSystem: '0052'
    };

    http({
      path: PATHS_ALIAS.THIRD_USER_LOGIN,
      params: params,
      header: {
        sendChl: 'hzsmk.h5',// 应用渠道(必填) 
        sendClient: 'hellohzsmk', //应用验证码(必填) string 
        clientCode: OTHER_INFO.clientCode
      },
      success: function (res) {
        // //console.log(res);
        wx.setStorageSync('accessToken', res.response.accessToken);
        wx.setStorageSync('userId', res.response.userId);
        wx.setStorageSync('mobile', res.response.mobile);
        _this.setData({
          token: res.response.accessToken,
          mobile: res.response.mobile,
          userId: res.response.userId,
        });
        _this.placeOrder();
      },
      fail: function (err) {
        wx.hideLoading();
        wx.showToast({
          title: '登录失败',
          icon: 'none'
        });
        // //console.log(err);
        if (err.code == 'PY0005') {    //跳转输入手机号登录
          wx.redirectTo({
            url: '/pages/phoneLogin/phoneLogin?fromPage=/pages/my/my',
          })
        }
      },
      complete: function () {

      }
    })
  },
  // 提交订单-二次支付
  placeOrder: function () {
    let _this = this;
    let orderDetail = this.data.orderDetail;
    let params = {
      accessToken: this.data.token,     //	用户令牌	string	必填
      actOrganizes: orderDetail.actOrganizes,     //	活动渠道方	string	必填
      activityId: orderDetail.activityId,     //	活动ID	string	必填
      mobile: this.data.mobile,     //	手机号	string	
      money: orderDetail.entryFee * 10 * 10,     //	报名费金额单位分	string	必填
      orderNo: orderDetail.orderNo,     //	订单号	string	必填
      realUserId: this.data.userId,     //	统一用户userId	string	必填
      theme: orderDetail.theme     //	活动主题	string	必填
    };
    http({
      path: PATHS_ALIAS.SECOND_PAY_ORDER,
      params: params,
      success: function (res) {
        _this.aggPay(res.response.orderInfo);
      },
      fail: function (err) {
        // //console.log(err);
        wx.showToast({
          title: err.msg,
          icon: 'none'
        })
      }
    });
  },
  // 调用平台组统一支付接口
  aggPay: function (orderInfo) {
    let _this = this;
    let orderObj = JSON.parse(utils.base64DecodeUnicode(orderInfo));
    // orderObj.order.thirdAppId = 'wxbb59b4862d99c420';
    //console.log(orderObj);
    let params = {
      openId: wx.getStorageSync('openId'),    //	微信openid，微信公众号支付时必传	string	
      order: orderObj.order,    //		订单信息	object	
      payType: 'WECHAT-SP',    //		支付方式	string	支付宝h5：ALIPAY 微信h5：WECHAT 微信公众号：WECHAT-OA 支付宝app: ALIPAY - APP 微信app：WECHAT-APP，微信小程序：WECHAT-SP
      thirdAppid: OTHER_INFO.appId
    };
    http({
      path: PATHS_ALIAS.AGG_PAY,
      params: params,
      header: {
        accessToken: this.data.token,
        clientCode: OTHER_INFO.clientCode, //测试100001 验证用 300016
        sendChl: 'hzsmk.h5',// 应用渠道(必填) 
        sendClient: 'hellohzsmk', //应用验证码(必填) string  
        sendDev: 'test',//设备号(必填) string  
        serialSeq: new Date().getTime() + this.data.userId, //流水号(必填) string
        userName: this.data.mobile
      },
      success: function (res) {
        //console.log(res);
        let tn = JSON.parse(res.response.tn);
        let paySign = tn.sign;
        //console.log(tn)
        wx.hideLoading();
        // 调用微信支付
        wx.requestPayment({
          'timeStamp': tn.timeStamp + "", //new Date().getTime(),
          'nonceStr': tn.nonce_str, //Math.random().toString(36).substr(2),
          'package': "prepay_id=" + tn.prepay_id, //'prepay_id=*',
          'signType': 'MD5',
          'paySign': paySign,
          'success': function (res) {
            // 支付成功后
            //console.log('支付成功:' + JSON.stringify(res));
            _this.confirmGroupOrder('success');
          },
          'fail': function (err) {
            //console.log(err);
            // 支付失败，或取消支付.跳转到订单详情
            if (err.errMsg == 'requestPayment:fail cancel') {
              wx.showToast({
                title: '取消支付',
                icon: 'none'
              })
            } else {
              wx.showToast({
                title: '支付失败',
                icon: 'none'
              });
            };
          }
        })
      },
      fail: function (err) {
        // //console.log(err);
        wx.hideLoading();
        wx.showToast({
          title: err.msg,
          icon: 'none'
        });
      }
    })
  },
  // 确认订单--支付成功回调   success-支付成功，fail-支付失败
  confirmGroupOrder: function (orderStatus) {
    let _this = this;
    let params = {
      mobile: this.data.mobile,    //	手机号	string	必填
      orderNo: this.data.orderNo,    //		订单号	string	必填
      orderStatus: orderStatus,    //		订单状态	string	必填，，success-支付成功，fail-支付失败
      realUserId: this.data.userId,    //		统一用户userId	string	必填
    };
    http({
      path: PATHS_ALIAS.CONFIRM_GROUP_ORDER,
      params: params,
      success: function (res) {
        //console.log(res)
        let groupId = res.response.groupId;
        // 参团者支付成功跳转到拼团详情
        if (groupId != 0 && orderDetail.groupLeader == 'N') {
          wx.navigateTo({
            url: `/pages/groupBuy/groupBuy?groupId=${res.response.groupId}`,
          });
        } else {
          _this.getOrderList(1);
        }
      },
      fail: function (err) {
        //console.log(err);
        // wx.navigateTo({
        //   url: `/pages/groupBuy/groupBuy?groupId=${res.response.groupId}`,
        // });
        _this.getOrderList(1);
      }
    })

  },
  // 支付结束*********************************************************************************

  onHide:function(){
    wx.hideLoading();
  }
})